//
//  YolandaDb.swift
//  foreign_swift
//
//  Created by hdr on 15-4-10.
//  Copyright (c) 2015年 hdr. All rights reserved.
//


class YolandaDb{
    
    static let version:UInt = 2
    static let db_file_name = "yolanda.db"
    static var db:SQLiteHandle!
    
    static func initDb(){
        
        let sqlite = SQLite(path: FileHelper.getAbsolutePath(db_file_name), version: version) {
            (db:SQLiteHandle, oldVersion:Int, newVersion:Int) -> Bool in
            //删除所有的表
            let error = db.dropAll()
            if error == .OK {
                
            }
        
            db.createTableIfNotExists(User)
            
            return true
        }
        let (db,error) = sqlite.open()
        if error == .OK {
            YolandaDb.db = db
        }else{
            println("数据库打开失败！！")
        }
        
    }
    
    static func saveUser(user:User){
        YolandaDb.db.insertOrReplace(into: User.tableName,params:[ "email":user.email,"serverId":user.serverId,"userType":user.userType,"height":user.height,"gender":user.gender,"birthday":user.birthday.stringWithFormat("yyyy-MM-dd"),"nickName":user.nickName,"accountName":user.accountName,"avatar":user.avatar])
    }
    
    static func getMasterUser()->User?{
        let rs = YolandaDb.db.select(["*"], from: User.tableName, Where: " userType = \(Const.USER_TYPE_MASTER) ")
        if let rs = rs {
            if rs.next {
                let user = Converter.rsToUser(rs)
                rs.close()
                return user
            }
            rs.close()
        }
        return nil
    }
    
    static func getAllUser()->[User]{
        let rs = YolandaDb.db.select(["*"], from: User.tableName, Where: nil)
        var users = [User]()
        if let rs = rs {
            while rs.next {
                let user = Converter.rsToUser(rs)
                users.append(user)
            }
            rs.close()
        }
        return users
    }
}